/**
 * 
 */
package com.caizi.socket.imagetool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author CAIZI
 * 
 */
public class ImageOper {

    public static Map<String, File> downloadImage(String httpUrl, String productId) throws Exception {
        File storeFile = null;
        File dir = new File("./images/");
        if (!dir.exists() && !dir.mkdirs()) {
            throw new Exception("creat dir failed!");
        }
        FileOutputStream output = null;
        try {
            String picUrl = getImageUrl(httpUrl);
            if (null == picUrl) {
                System.out.println("货号为:" + productId + "的图片未下载" + "！！！");
                return null;
            }
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(picUrl);
            client.executeMethod(get);
            storeFile = new File("./images/" + productId + ".png");
            output = new FileOutputStream(storeFile);
            // 得到网络资源的字节数组,并写入文件
            output.write(get.getResponseBody());
            output.flush();
            System.out.println("已下载货号为:" + productId + "的图片至:" + storeFile.getAbsolutePath());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                if (null != output) {
                    output.close();
                }
            } catch (IOException e) {
                System.out.println(e.getMessage());
            }
        }
        Map<String, File> fileMap = new HashMap<String, File>();
        fileMap.put(productId, storeFile);
        return fileMap;
    }

    /**
     * 获取图片地址
     * 
     * @param httpUrl
     * @return
     * @throws Exception
     */
    private static String getImageUrl(String httpUrl) throws Exception {
        String picUrl = null; // 图片地址
        StringBuffer html = fetchHtml(httpUrl);
        // 将字符串解析为html文档
        Document doc = Jsoup.parse(html.toString());
        // 获取img标签
        Elements es = doc.getElementsByTag("img");
        // 获取每一个img标签data-ks-lazyload的内容，也就是图片地址
        for (Iterator<Element> i = es.iterator(); i.hasNext();) {
            Element e = i.next();
            String r = e.attr("data-ks-lazyload");
            if (null != r && r.startsWith("http://img") && r.endsWith(".jpg")) {
                picUrl = r;
            }
        }
        // 获取不到data-ks-lazyload的内容，则获取src的内容
        if (null == picUrl) {
            for (Iterator<Element> i = es.iterator(); i.hasNext();) {
                Element e = i.next();
                String r = e.attr("src");
                if (null != r && r.startsWith("http://img") && r.endsWith(".jpg")) {
                    picUrl = r;
                }
            }
        }
        return picUrl;
    }

    /**
     * 获取网页内容
     * 
     * @param httpUrl
     * @return
     * @throws Exception
     */
    private static StringBuffer fetchHtml(String httpUrl) throws Exception {
        StringBuffer data = new StringBuffer();
        String currentLine;
        // 打开输入流
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(getInputStream(httpUrl), "GBK"));
            // 读取数据
            while ((currentLine = reader.readLine()) != null) {
                data.append(currentLine);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw e;
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
        return data;
    }

    private static InputStream getInputStream(String httpUrl) throws Exception {
        // 网页Url
        URL url = new URL(httpUrl);
        URLConnection uc = url.openConnection();
        uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        return uc.getInputStream();
    }
}
